package cn.zxhysy.booksmall.config;

import cn.zxhysy.booksmall.controller.BasicController;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.HashMap;
import java.util.Map;

public class LoginHttpSessionListener implements HttpSessionListener {
  private static final Map<String, HttpSession> SESSION_CACHE = new HashMap<String, HttpSession>();

  /**
   * Session 创建
   */
  @Override
  public void sessionCreated(HttpSessionEvent se) {
    regist(se.getSession(), se.getSession().getAttribute(BasicController.USER_REDIS_SESSION).toString());
  }

  /**
   * Session 销毁
   */
  @Override
  public void sessionDestroyed(HttpSessionEvent se) {
    remove(se.getSession().getAttribute(BasicController.USER_REDIS_SESSION).toString());
  }
  
  /**
   * Session 获取
   * @param sessionId
   * @return
   */
  public static HttpSession getSession(String sessionId) {
    return SESSION_CACHE.get(sessionId);
  }
  
  /**
   * 注册Session
   * @param session
   */
  public static void regist(HttpSession session, String uniqueToken) {
    if (null == session) {
      return;
    }
    synchronized (SESSION_CACHE) {
      if (null == SESSION_CACHE.get(uniqueToken)) {
        SESSION_CACHE.put(uniqueToken, session);
      }
    }
  }
  
  /**
   * 清除Session
   * @param sessionId
   */
  public static void remove(String sessionId) {
    if (null == sessionId) {
      return;
    }
    synchronized (SESSION_CACHE) {
      if (null != SESSION_CACHE.get(sessionId)) {
        SESSION_CACHE.remove(sessionId);
      }
    }
  }
}
